package com.example.goodsass.controller;

import com.example.goodsass.common.BaseResponse;
import com.example.goodsass.common.BusinessException;
import com.example.goodsass.common.ErrorCode;
import com.example.goodsass.common.MinIOUtils;
import com.example.goodsass.constans.enums.UploadType;
import com.example.goodsass.domain.FileInfo;
import com.example.goodsass.domain.User;
import com.example.goodsass.dto.UploadParam;
import com.example.goodsass.service.FileInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Resource
    private FileInfoService fileInfoService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public BaseResponse<String> upload(@RequestPart("file") MultipartFile file, UploadParam uploadType, HttpServletRequest request) {
        String url = "";
        try {
            User loginUser = (User)request.getSession().getAttribute("loginUser");
            if (loginUser == null){
                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"请先登录");
            }
            UploadType byCode = UploadType.getByCode(uploadType.getUploadType());
            if (byCode == null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"上传类型错误");
            }
            // 检查文件名是否包含特殊字符
            String originalFilename = file.getOriginalFilename();
            if (originalFilename != null && containsSpecialCharacters(originalFilename)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件名不能包含特殊字符（如#、?、&等）");
            }
            url = MinIOUtils.uploadFileAndGetPermanentUrl(byCode.getValue().toLowerCase(), file, file.getOriginalFilename(), file.getContentType());
            FileInfo build = FileInfo.builder().createUser(loginUser.getId()).url(url).fileName(file.getOriginalFilename()).uploadType(byCode.getCode()).build();
            fileInfoService.save(build);
        } catch (Exception e) {
            log.error("上传失败",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"上传失败");
        }
        return BaseResponse.success(url);
    }

    /**
     * 检查文件名是否包含特殊字符
     */
    private boolean containsSpecialCharacters(String filename) {
        // 定义不允许的特殊字符
        String specialChars = "#?&=+%\\/:*\"<>|";
        for (int i = 0; i < specialChars.length(); i++) {
            if (filename.contains(String.valueOf(specialChars.charAt(i)))) {
                return true;
            }
        }
        return false;
    }
}
